import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Search, Plus, Shield } from "lucide-react";
import { EmergencyMeasureTemplateAPI } from "@/api/EmergencyMeasureTemplate";

export default function EmergencyMeasureImportModal({
  isOpen,
  onClose,
  onImport,
}) {
  const [templates, setTemplates] = useState([]);
  const [filteredTemplates, setFilteredTemplates] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedTemplates, setSelectedTemplates] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (isOpen) {
      loadTemplates();
    }
  }, [isOpen]);

  const loadTemplates = async () => {
    setIsLoading(true);
    try {
      const templatesData = await EmergencyMeasureTemplateAPI.getList();
      console.log("加载的应急措施模板:", templatesData);
      setTemplates(Array.isArray(templatesData.data) ? templatesData.data : []);
    } catch (error) {
      console.error("加载应急措施模板失败:", error);
      setTemplates([]);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (searchTerm) {
      const filtered = templates.filter(
        (template) =>
          template.incidentType
            ?.toLowerCase()
            .includes(searchTerm.toLowerCase()) ||
          template.description
            ?.toLowerCase()
            .includes(searchTerm.toLowerCase()) ||
          template.category?.toLowerCase().includes(searchTerm.toLowerCase())
      );
      setFilteredTemplates(filtered);
    } else {
      setFilteredTemplates(templates);
    }
  }, [templates, searchTerm]);

  const toggleTemplate = (template) => {
    setSelectedTemplates((prev) => {
      const exists = prev.find((t) => t.id === template.id);
      if (exists) {
        return prev.filter((t) => t.id !== template.id);
      } else {
        return [...prev, template];
      }
    });
  };

  const handleImport = () => {
    console.log(selectedTemplates, "selectedTemplatesselectedTemplates");
    if (selectedTemplates.length > 0) {
      // 转换模板为方案的应急措施格式
      const emergencyMeasures = selectedTemplates.map((template) => ({
        id: `imported_${template.id}_${Date.now()}`,
        incidentType: template.incidentType,
        description: template.description,
        immediateActions: template.immediateActions,
        requiredEquipment: template.requiredEquipment || "",
        responsiblePersonRole: template.responsiblePersonRole || "",
      }));
      onImport(emergencyMeasures);
      setSelectedTemplates([]);
      onClose();
    }
  };

  const getCategoryLabel = (category) => {
    const labels = {
      personnelInjury: "人员伤害",
      equipmentFailure: "设备故障",
      fireAccident: "火灾事故",
      electricShock: "触电事故",
      fallFromHeight: "高处坠落",
      environmentalIncident: "环境事件",
      trafficAccident: "交通事故",
      other: "其他",
    };
    return labels[category] || category;
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Shield className="w-5 h-5 text-orange-600" />
            从知识库选择应急措施
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="搜索事故类型、描述或分类..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>

          {isLoading ? (
            <div className="text-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-orange-600 mx-auto mb-4"></div>
              <p className="text-gray-500">加载应急措施模板中...</p>
            </div>
          ) : filteredTemplates.length === 0 ? (
            <div className="text-center py-8">
              <Shield className="w-12 h-12 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-500 mb-2">
                {templates.length === 0
                  ? "暂无应急措施模板"
                  : "未找到匹配的模板"}
              </p>
              {templates.length === 0 && (
                <p className="text-sm text-gray-400">
                  请先在知识库中添加应急措施模板
                </p>
              )}
            </div>
          ) : (
            <div className="grid gap-3 max-h-96 overflow-y-auto">
              {filteredTemplates.map((template) => {
                const isSelected = selectedTemplates.find(
                  (t) => t.id === template.id
                );
                return (
                  <Card
                    key={template.id}
                    className={`cursor-pointer transition-colors ${
                      isSelected
                        ? "bg-orange-50 border-orange-200"
                        : "hover:bg-gray-50"
                    }`}
                    onClick={() => toggleTemplate(template)}
                  >
                    <CardHeader className="pb-2">
                      <CardTitle className="text-sm flex items-center justify-between">
                        <span>{template.incidentType}</span>
                        <div className="flex items-center gap-2">
                          <Badge variant="outline">
                            {getCategoryLabel(template.category)}
                          </Badge>
                          {isSelected && (
                            <Badge className="bg-orange-100 text-orange-800">
                              已选择
                            </Badge>
                          )}
                        </div>
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="pt-0">
                      <p className="text-sm text-gray-600 mb-2">
                        {template.description}
                      </p>
                      {template.immediateActions &&
                        template.immediateActions.length > 0 && (
                          <div className="text-xs text-gray-500">
                            <strong>立即处置措施：</strong>
                            {template.immediateActions}
                            {/* {template.immediateActions.slice(0, 2).join("; ")}
                            {template.immediateActions.length > 2 && "..."} */}
                          </div>
                        )}
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}

          {selectedTemplates.length > 0 && (
            <div className="border-t pt-4">
              <p className="text-sm text-gray-600 mb-2">
                已选择 {selectedTemplates.length} 个应急措施模板
              </p>
              <div className="flex flex-wrap gap-2">
                {selectedTemplates.map((template) => (
                  <Badge key={template.id} variant="secondary">
                    {template.incidentType}
                  </Badge>
                ))}
              </div>
            </div>
          )}

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button variant="outline" onClick={onClose}>
              取消
            </Button>
            <Button
              onClick={handleImport}
              disabled={selectedTemplates.length === 0}
              className="bg-orange-600 hover:bg-orange-700"
            >
              <Plus className="w-4 h-4 mr-2" />
              导入选中的措施 ({selectedTemplates.length})
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
